package com.shenmazong.order.recv;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.shenmazong.order.db.TbMessage;
import com.shenmazong.vo.PublicMessageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: MessageRecv
 * @date 2022/8/5 15:25
 */

@Component
@Slf4j
public class MessageRecv {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(queues = "public_login_queue")
    public void onLoginMessage(Message message, Channel channel) throws IOException {
        //--1 把消息转换为String
        byte[] body = message.getBody();
        String msg = new String(body);

        //--2 把String转成对象
        PublicMessageVo messageVo = JSON.parseObject(msg, PublicMessageVo.class);

        //--3 防止重复消息
        Long id = messageVo.getId();
        String key = "messsage_" + id;
        if(redisTemplate.hasKey(key)) {
            log.info("消息已经被消费了:"+id);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        //--4 把登录日志写入到MongoDB中
        String logMessage = messageVo.getMessage();
        log.info("onLoginMessage:"+logMessage);

        TbMessage tbMessage = new TbMessage();
//        tbMessage.setId(messageVo.getId());
//        tbMessage.setType(messageVo.getType());
//        tbMessage.setMessage(messageVo.getMessage());
        BeanUtils.copyProperties(messageVo, tbMessage);
        tbMessage.setCreateTime(new Date());

        mongoTemplate.save(tbMessage);
        log.info("onLoginMessage:消息已经存入MongoDB中了...");

        //--5 设置消息的ID到redis中，防止其他消费者消费
        redisTemplate.opsForValue().set(key, key, 5, TimeUnit.MINUTES);

        //--6 从队列中删除消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
